const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 3000;

const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf',
    '.wasm': 'application/wasm'
};

const server = http.createServer((req, res) => {
    // CORS 头设置 - 支持跨域访问
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Cache-Control', 'no-cache'); // 禁用缓存，确保更新

    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    // 解析URL，移除查询参数
    const urlParts = req.url.split('?');
    let cleanUrl = urlParts[0];
    
    let filePath = '.' + cleanUrl;
    if (filePath === './' || filePath === '.' || cleanUrl === '/') {
        filePath = './index.html';
    }
    
    // 特殊处理：如果请求的是目录，返回index.html
    if (cleanUrl.endsWith('/')) {
        filePath = '.' + cleanUrl + 'index.html';
    }
    
    console.log(`📁 请求URL: ${req.url} -> 文件路径: ${filePath}`);

    const extname = String(path.extname(filePath)).toLowerCase();
    const mimeType = mimeTypes[extname] || 'application/octet-stream';

    fs.readFile(filePath, (error, content) => {
        if (error) {
            if (error.code === 'ENOENT') {
                console.log(`文件不存在: ${filePath}`);
                // 如果请求的是根路径或包含特殊参数，返回index.html
                if (cleanUrl === '/' || req.url.includes('id=') || req.url.includes('vscodeBrowserReqId=')) {
                    fs.readFile('./index.html', (indexError, indexContent) => {
                        if (indexError) {
                            res.writeHead(500);
                            res.end('无法加载index.html', 'utf-8');
                        } else {
                            res.writeHead(200, { 'Content-Type': 'text/html' });
                            res.end(indexContent, 'utf-8');
                        }
                    });
                    return;
                }
                // 文件不存在，但如果是图片文件，返回占位符
                if (['.jpg', '.png', '.gif', '.svg'].includes(extname)) {
                    // 返回占位符 SVG
                    const placeholder = `
                        <svg width="600" height="400" xmlns="http://www.w3.org/2000/svg">
                            <rect width="100%" height="100%" fill="#1a1f2e"/>
                            <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" 
                                  font-family="Arial, sans-serif" font-size="20" fill="#ffffff" opacity="0.7">
                                图片加载中...
                            </text>
                        </svg>
                    `;
                    res.writeHead(200, { 'Content-Type': 'image/svg+xml' });
                    res.end(placeholder, 'utf-8');
                } else {
                    res.writeHead(404);
                    res.end(`文件未找到: ${req.url}`, 'utf-8');
                }
            } else {
                res.writeHead(500);
                res.end(`服务器错误: ${error.code}`, 'utf-8');
            }
        } else {
            res.writeHead(200, { 'Content-Type': mimeType });
            res.end(content, 'utf-8');
        }
    });
});

server.listen(PORT, () => {
    console.log(`🚀 时空回音游戏服务器启动成功！`);
    console.log(`🌐 访问地址: http://localhost:${PORT}`);
    console.log(`📁 服务目录: ${__dirname}`);
    console.log(`⚡ 服务器正在运行...`);
    console.log(`🔧 支持预览器特殊URL参数处理`);
});

server.on('error', (err) => {
    console.error('服务器启动失败:', err);
});